package com.zhiqianbao.activity;

import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.zhiqianbao.R;
import com.zhiqianbao.utils.Constants;
import cn.trinea.android.common.util.StringUtils;

/**
 * Created by liang on 2016/1/8.
 */
public class BindLianlianActivity extends BaseActivity {
    WebView mWebView;
    TextView textviewRegisterTitle;
    RelativeLayout titleLayout;

    String url;
    String title;
    String encoding;
    String method;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_contract);
        Intent intent = getIntent();

        url = (String) intent.getSerializableExtra("url");
        title = (String) intent.getSerializableExtra("title");
        method = (String) intent.getSerializableExtra("method");
        encoding = (String) intent.getSerializableExtra("encoding");
        if (StringUtils.isBlank(method)) {
            method = "GET";
        }
        if (StringUtils.isBlank(encoding)) {
            encoding = "UTF-8";
        }
        init();
        initView();
    }

    @TargetApi(Build.VERSION_CODES.KITKAT)
    private void initView() {
         mWebView=(WebView)findViewById(R.id.mWebView);
         textviewRegisterTitle=(TextView)findViewById(R.id.textview_register_title);
         titleLayout=(RelativeLayout)findViewById(R.id.relativeLayout_dialog_cantract_title);

        WebSettings webSettings = mWebView.getSettings();
        //设置WebView属性，能够执行Javascript脚本
        webSettings.setJavaScriptEnabled(true);
        //设置可以访问文件
        webSettings.setAllowFileAccess(false);
        //设置支持缩放
        webSettings.setBuiltInZoomControls(false);
        //设置字体编码
        webSettings.setDefaultTextEncodingName(encoding);


        //加载需要显示的网页
        if (!url.startsWith("http:") && !url.startsWith("https:")) {
            url = Constants.API_ROOT + url;
        }

        if ("POST".equalsIgnoreCase(method)) {
            String uri = url.contains("?") ? url.substring(0, url.indexOf("?")) : url;
            String paramStr = url.contains("?") ? url.substring(url.indexOf("?") + 1) : "";
            try {
                paramStr = paramStr.replaceAll("\\+", "%2B");
            } catch (Exception e) {
                e.printStackTrace();
            }
            mWebView.postUrl(uri, paramStr.getBytes());

        } else {
            Log.i(getClass().getSimpleName(), "url===" + url);
            mWebView.loadUrl(url);
        }
        //覆盖WebView默认使用第三方或系统默认浏览器打开网页的行为，使网页用WebView打开
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                //返回值是true的时候控制去WebView打开，为false调用系统浏览器或第三方浏览器
                Log.i("WebViewClient", "url:" + url);
                view.loadUrl(url);
                return true;
            }
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                Log.i("WebViewClient", "onPageStarted--url:" + url);
                super.onPageStarted(view, url, favicon);
            }
            @Override
            public void onPageFinished(WebView view, String url) {
                Log.i("WebViewClient", "onPageFinished--url:" + url);
                super.onPageFinished(view, url);
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                // 不要使用super，否则有些手机访问不了，因为包含了一条 handler.cancel()，默认取消ssl证书
                // super.onReceivedSslError(view, handler, error);

                // 接受所有网站的证书，忽略SSL错误，执行访问网页
                handler.proceed();
            }

            @TargetApi(Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
                super.onReceivedHttpError(view, request, errorResponse);

            }

        });
        mWebView.setWebChromeClient(new MyWebChromeClient());
        mWebView.addJavascriptInterface(new CaccelInterface(), "webview");
        textviewRegisterTitle.setText("连连支付");
        titleLayout.setVisibility(View.VISIBLE);
    }

    /**
     * 浏览器可弹窗
     *
     * @author Administrator
     */
    final class MyWebChromeClient extends WebChromeClient {
        @Override
        public boolean onJsConfirm(WebView view, String url, String message,
                                   final JsResult result) {
            showShortToast1(message);
            return true;
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
//            if(title.equals("银行卡认证")){
//                titleLayout.setVisibility(View.GONE);
//            }
//            else{
//                titleLayout.setVisibility(View.VISIBLE);
//            }
        }
    }

    public class CaccelInterface {
        @JavascriptInterface
        public void cancel() {
            BindLianlianActivity.this.finish();
        }
    }

}
